package com.feishi.core.util.common.lecode.thread;

import java.util.function.IntConsumer;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: caixq
 * Date: 2020-08-19
 * Time: 下午3:27
 */
public class ZeroEvenOdd {
    public static void main(String[] args) {
        ZeroEvenOdd zeroEvenOdd=new ZeroEvenOdd(5);
        new Thread(()-> {
            try {
                zeroEvenOdd.zero(System.out::print);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(()-> {
            try {
                zeroEvenOdd.odd(System.out::print);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(()-> {
            try {
                zeroEvenOdd.even(System.out::print);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }



    private int n;

    public ZeroEvenOdd(int n) {
        this.n = n;
    }

    int index = 0;
    boolean status = true;

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void zero(IntConsumer printNumber) throws InterruptedException {
        synchronized (this) {
            while (index < n) {

//                System.out.println(">>>>>"+status+"::");
                if (!status) {
                    this.wait();
                } else {
                    status = !status;
                    printNumber.accept(0);
                    this.notifyAll();
                }
            }
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        synchronized (this) {
            while (index < n) {
//                System.out.println(status+"::"+index);
                if (!status && index % 2 == 1) {
                    //status = !status;
                    printNumber.accept(++index);
                    this.notifyAll();
                }else {
                    this.wait();
                }
            }
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        synchronized (this) {
            while (index < n) {
//                System.out.println(status+"::"+index);
                if (!status && index % 2 == 0) {
                    status = !status;
                    printNumber.accept(++index);
                    this.notifyAll();
                }else {
                    this.wait();
                }
            }
        }
    }
}